import type { UserConfig, ConfigEnv } from 'vite';
import { loadEnv } from 'vite';
import { resolve } from 'path';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';

const root: string = process.cwd();

function pathResolve(dir: string) {
    return resolve(__dirname, '.', dir);
}

export default ({ command, mode }: ConfigEnv): UserConfig => {
    const viteEnv = loadEnv(mode, root);
    const { VITE_PORT, VITE_PUBLIC_PATH, VITE_DROP_CONSOLE, VITE_LEGACY } = viteEnv;

    const isBuild = command === 'build';

    return {
        base: VITE_PUBLIC_PATH,
        root,
        alias: [
            {
                find: /^\/@\//,
                replacement: pathResolve('src') + '/',
            },
        ],
        server: {
            port: Number(VITE_PORT),
            hmr: {
                overlay: true,
            },
            open: true
        },
        build: {
            target: 'modules', // modules
            polyfillDynamicImport: Boolean(VITE_LEGACY),
            terserOptions: {
                compress: {
                    keep_infinity: true,
                    drop_console: Boolean(VITE_DROP_CONSOLE),
                },
            },
        },
        plugins: [
            vue(),
            vueJsx()
        ],
        optimizeDeps: {
            include: ['@iconify/iconify'],
        },
    }
}